﻿// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using System.Security.Cryptography;
using System.Text;

namespace BlazorAdmin.Security.Cryptography
{
    /// <summary>
    /// 加密算法操作类
    /// </summary>
    public class LgbCryptography
    {
        /// <summary>
        /// 生成 Salt(密码盐) 方法
        /// </summary>
        /// <param name="length">密码盐长度，默认36</param>
        /// <returns></returns>
        public static string GenerateSalt(int length = 36)
        {
            RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create();
            byte[] array = new byte[length];
            randomNumberGenerator.GetBytes(array);
            return Convert.ToBase64String(array);
        }

        /// <summary>
        /// 计算哈希值方法 内部使用 SHA256CryptoServiceProvider 算法
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <param name="salt">密码盐</param>
        /// <returns></returns>
        public static string ComputeHash(string data, string salt)
        {
            return ComputeHash(data, salt, SHA256.Create());
        }

        /// <summary>
        /// 计算哈希值方法
        /// </summary>
        /// <param name="data">原始数据</param>
        /// <param name="salt">密码盐</param>
        /// <param name="algorithm">算法实例</param>
        /// <returns></returns>
        public static string ComputeHash(string data, string salt, HashAlgorithm algorithm)
        {
            byte[] bytes = Encoding.UTF8.GetBytes($"{data}{salt}");
            return Convert.ToBase64String(algorithm.ComputeHash(bytes));
        }
    }
}